import { onBeforeUnmount } from 'vue'
// import { getToken } from '@/utils/auth'

const useSocket = ():any => {
  let socket: WebSocket

  onBeforeUnmount(() => {
    // 销毁监听
    socket.onclose = close
  })

  const init = (path: string) => {
    if (typeof (WebSocket) === 'undefined') {
      alert('您的浏览器不支持socket')
    } else {
      // 实例化socket
      socket = new WebSocket(path)
      // 监听socket连接
      socket.onopen = open
      // 监听socket错误信息
      socket.onerror = error
      // 监听socket消息
      socket.onmessage = getMessage
      // 监听socket关闭
      socket.onclose = close
    }
  }

  const open = () => {
    console.log('socket连接成功')
    send(JSON.stringify({
      clientId: 'tm-0000001', // 天猫账号，不可更改，每个账号只能绑定一个天猫精灵
      cmd: 1, // 1登录  4消息  0OK
      result: 'login'
    }))
  }

  const error = () => {
    console.log('socket连接错误')
  }

  const getMessage = (msg: { data: string }) => {
    console.log('getMessage: ', msg.data)
  }

  const send = (msg: string) => {
    console.log('socket: ', socket)
    if (socket.readyState !== 1) {
      console.error('ws未连接')
      return
    }
    console.log('msg: ', msg)
    socket.send(msg)
  }

  const close = () => {
    console.log('socket断开连接')
  }

  return {
    init,
    send
  }
}

export default useSocket
